//
//  ZPImageButton.m
//  Dresshere_S2
//
//  Created by ZhangPeng on 2018/4/11.
//  Copyright © 2018年 lishan. All rights reserved.
//

#import "ZPImageButton.h"

@interface ZPImageButton()

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UILabel *titleLabel;

@end

@implementation ZPImageButton

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title titleFont:(UIFont *)font titleColor:(UIColor *)titleColor image:(UIImage *)image buttonBackgroundColor:(UIColor *)backgroundColor
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = backgroundColor;
        
        CGFloat imageW = frame.size.height / 2; //图片的高度为按钮高度的一半
        CGFloat titleLabelW = [title widthForFont:font]; //计算titleLabel的宽度
        CGFloat imageAndTitleLabelSpace = 5; //图片与titleLabel的间隙
        CGFloat contentTotalW = imageW + imageAndTitleLabelSpace + titleLabelW; // 视图内容总宽度
        CGFloat contentLeftSpace = (frame.size.width - contentTotalW) / 2; // 视图内容左边距离
 
        // 初始化视图
        if (!self.imageView) {
            self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(contentLeftSpace, imageW / 2, imageW, imageW)];
            self.imageView.image = image;
            self.imageView.contentMode = UIViewContentModeScaleAspectFit;
            [self addSubview:self.imageView];
        }
        if (!self.titleLabel) {
            self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.imageView.right + imageAndTitleLabelSpace, 0, titleLabelW, frame.size.height)];
            self.titleLabel.text = title;
            self.titleLabel.textColor = titleColor;
            self.titleLabel.font = font;
            [self addSubview:self.titleLabel];
        }
        
    }
    return self;
}

@end
